#include "add.h"
#include "ui_add.h"
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
#include <QMessageBox>
#include <QDate> // 引入日期处理头文件
#include "dbmanager.h"
add::add(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::add)
{
    ui->setupUi(this);
}

add::~add()
{
    delete ui;
}


void add::on_pushButton_addstu_clicked()
{
    qDebug() << "按钮被点击！";

    // 获取各输入框内容
    QString studentId = ui->lineEdit_stuid->text();
    QString studentName = ui->lineEdit_stuname->text();
    QString gender = ui->lineEdit_stugender->text();
    QString contact = ui->lineEdit_contact->text();
    QString major = ui->lineEdit_major->text();
    QString building = ui->lineEdit_building->text();
    QString dorm_room = ui->lineEdit_dorm_room->text();
    QString enrollDateStr = ui->lineEdit_eoll->text();
    QString password = ui->lineEdit_password->text(); // 获取密码输入框内容

    // 简单校验，确保关键信息不为空
    if (studentId.isEmpty() || studentName.isEmpty()) {
        QMessageBox::warning(this, "输入错误", "学号和姓名不能为空！");
        return;
    }

    // 日期格式校验
    QDate enrollDate = QDate::fromString(enrollDateStr, "yyyy-MM-dd"); // 假设日期格式为yyyy-MM-dd
    if (!enrollDate.isValid()) {
        QMessageBox::warning(this, "日期格式错误", "入学时间格式不正确，请按照yyyy-MM-dd格式输入！");
        return;
    }

    QSqlDatabase db = DBManager::instance()->getDatabase();

    if (!db.open()) {
        qDebug() << "数据库连接失败: " << db.lastError().text();
        QMessageBox::critical(this, "数据库连接错误", "无法连接到数据库，请检查配置！");
        return;
    }

    // 构建插入语句并执行，补充表中其他字段默认值
    QSqlQuery query(db);
    query.prepare("INSERT INTO student (student_id, student_name, gender, contact, major,building,dorm_room, enroll_date, stu_password) "
                  "VALUES (:student_id, :student_name, :gender, :contact, :major, :building,:dorm_room,:enroll_date, :password)");
    query.bindValue(":student_id", studentId);
    query.bindValue(":student_name", studentName);
    query.bindValue(":gender", gender);
    query.bindValue(":contact", contact);
    query.bindValue(":major", major);
    query.bindValue(":building", building);
    query.bindValue(":dorm_room", dorm_room);
    query.bindValue(":enroll_date", enrollDateStr);
    query.bindValue(":password", password); // 绑定密码

    if (query.exec()) {
        qDebug() << "学生信息添加成功";
        QMessageBox::information(this, "成功", "学生信息已成功添加到数据库！");
        // 关闭当前窗口（可根据实际需求调整，比如重置输入框等操作）
        this->close();
    } else {
        qDebug() << "学生信息添加失败: " << query.lastError().text();
        QMessageBox::critical(this, "添加失败", "添加学生信息时出现错误，请查看错误信息！");
    }

    // 关闭数据库连接
    db.close();
}


void add::on_pushButton_exit_clicked()
{
    this->close();
}

